package com.aw.baselib.widgets

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.widget.ProgressBar
import com.aw.baselib.util.AwConvertUtil
import com.aw.baselib.util.AwLog

/**
 * @author : hzw
 * @date : 2021/8/12
 */
class MyProgressView : ProgressBar {
    private var text: String? = null
    private var mPaint: Paint? = null

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        // TODO Auto-generated constructor stub
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        // TODO Auto-generated constructor stub
        init()
    }

    constructor(context: Context?) : super(context) {
        // TODO Auto-generated constructor stub
        init()
    }

    @Synchronized
    override fun setProgress(progress: Int) {
        setText(progress)
        super.setProgress(progress)
    }

    @SuppressLint("ResourceAsColor")
    @Synchronized
    override fun onDraw(canvas: Canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas)
        val rect = Rect()
        mPaint!!.getTextBounds(text, 0, text!!.length, rect)
        //        int x = getWidth()/2 ;
//        int y = getHeight()/2;
        AwLog.d(
            "===>getProgress: " + progress + " ,getWidth(): " + width + " ,rect.centerX(): " + rect.centerX()
                    + " ,rect.left: " + rect.left + " ,rect.right: " + rect.right
                    + " ,百分比结果: " + (width * AwConvertUtil.div(
                progress.toDouble(),
                max.toDouble(),
                5
            )).toInt()
        )
        var x = width / 2 - rect.centerX()
        val y = height / 2 - rect.centerY()
        if (progress > 10) {
            x = (width * AwConvertUtil.div(
                progress.toDouble(),
                max.toDouble(),
                5
            )).toInt() - rect.right - 20
        }
        canvas.drawText(text!!, x.toFloat(), y.toFloat(), mPaint!!)
    }

    private fun init() {
        mPaint = Paint()
        mPaint!!.textSize = 30f
        mPaint!!.color = Color.BLACK
    }

    fun setText(progress: Int) {
        val i = progress * 100 / this.max
        text = "$i%"
    }
}